package com.yb.xczx.cloud.auth.generator;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.time.Instant;
import java.util.UUID;


@Slf4j
public class XczxOAuth2AuthorizationCodeGenerator implements OAuth2TokenGenerator<OAuth2AuthorizationCode> {


	@Nullable
	@Override
	public OAuth2AuthorizationCode generate(OAuth2TokenContext context) {
		if (context.getTokenType() == null ||
				!OAuth2ParameterNames.CODE.equals(context.getTokenType().getValue())) {
			return null;
		}
		Instant issuedAt = Instant.now();
		String authCode = UUID.randomUUID().toString().substring(0, 4);
		log.info("authCode:{}",authCode);
		Instant expiresAt = issuedAt.plus(context.getRegisteredClient().getTokenSettings().getAuthorizationCodeTimeToLive());
		return new OAuth2AuthorizationCode(authCode, issuedAt, expiresAt);
	}

}